const axios = require('axios');

// 配置基础URL
const baseURL = 'http://localhost:3003/api';
const api = axios.create({
  baseURL: baseURL
});

// 新用户注册信息
const newUser = {
  username: 'apitestuser',
  phone: '13912345678',
  password: 'apitestpassword'
};

const testBill = {
  category_id: 1,
  amount: 100.50,
  type: 'expense',
  bill_date: '2025-10-10',
  title: '测试账单',
  description: '测试账单描述'
};

async function testAPI() {
  try {
    console.log('开始测试 FinanceApp API...');
    
    // 1. 用户注册
    console.log('\n1. 用户注册...');
    try {
      const registerResponse = await api.post('/users/register', newUser);
      console.log('注册成功:', registerResponse.data.message);
    } catch (error) {
      if (error.response && error.response.status === 400) {
        console.log('用户可能已存在:', error.response.data.error);
      } else {
        throw error;
      }
    }
    
    // 2. 用户登录
    console.log('\n2. 用户登录...');
    const loginResponse = await api.post('/users/login', {
      phone: newUser.phone,
      password: newUser.password
    });
    console.log('登录成功:', loginResponse.data.message);
    const token = loginResponse.data.token;
    console.log('Token:', token);
    
    // 设置认证头
    api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    
    // 3. 创建账单
    console.log('\n3. 创建账单...');
    const createBillResponse = await api.post('/bills', testBill);
    console.log('账单创建成功:', createBillResponse.data);
    
    // 4. 获取账单列表
    console.log('\n4. 获取账单列表...');
    const getBillsResponse = await api.get('/bills');
    console.log('账单列表获取成功，共', getBillsResponse.data.bills.length, '条记录');
    
    // 5. 获取预算列表
    console.log('\n5. 获取预算列表...');
    const getBudgetsResponse = await api.get('/budgets');
    console.log('预算列表获取成功');
    
    // 6. 获取报表
    console.log('\n6. 获取报表...');
    const getReportsResponse = await api.get('/reports');
    console.log('报表列表获取成功');
    
    console.log('\n所有测试完成！');
  } catch (error) {
    console.error('测试过程中出现错误:');
    if (error.response) {
      console.error('状态码:', error.response.status);
      console.error('错误信息:', error.response.data);
    } else {
      console.error('错误:', error.message);
    }
  }
}

testAPI();